package cn.edu.scau.sec.caixiaoqing.singleton;

import java.util.ArrayList;
/**
 * 实现饿汉式单例模式（在未被调用前创建实例，防止在多线程情况下出现错误）
 */
public class Marshall {
    private String name;

    private static ArrayList<Marshall> select = new ArrayList<>();
    private static ArrayList<Marshall> marshalls = new ArrayList<>();
    static {
        String[] marshallNames ={"朱德","彭德怀","林彪","刘伯承","刘伯承","贺龙","陈毅","罗荣桓","徐向前","聂荣臻","叶剑英"};
        for (int i = 0;i<marshallNames.length;i++ ) {
            marshalls.add(new Marshall(marshallNames[i]));
        }
    }

    public String getName() {
        return name;
    }

    private Marshall(String name){
        this.name = name;
    }

    public static Marshall getInstance(String name){
        for (Marshall marshall: marshalls) {
            if (marshall.getName() == name){
                boolean flag = true;
                for (Marshall mar : select){
                    if (mar == marshall) flag = false;
                    break;
                }
                if (flag) select.add(marshall);
                return marshall;
            }
        }

        return null;
    }

    public static void printMarshalls(){
        System.out.print("您已创建的元帅的名单：");
        for (Marshall marshall: select) {
            System.out.print(marshall.getName()+";");
        }
        System.out.println();
    }
}